package com.demo.automic;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

public class DecimalAccountCas implements DecimalAccount {
    public static void main(String[] args) {
        DecimalAccountCas decimalAccountCas = new DecimalAccountCas(new BigDecimal(10000));
        DecimalAccount.demo(decimalAccountCas);
    }
    private AtomicReference<BigDecimal> balance;
    //引用类型 保护bigDecimal类型的共享变量的线程安全

    public DecimalAccountCas(BigDecimal balance) {
        this.balance = new AtomicReference<>(balance);
    }

    @Override
    public BigDecimal getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        while (true) {
            BigDecimal pre = balance.get();
            BigDecimal next = pre.subtract(amount);
            if(balance.compareAndSet(pre, next)) {
                //比较并设置值，成功则跳出循环
                break;
            }
        }
    }
}
